<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>动态线程池监控系统</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-zoom@2.0.1/dist/chartjs-plugin-zoom.umd.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns@3.0.0/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
        }

        .header {
            text-align: center;
            color: white;
            margin-bottom: 30px;
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }

        .header p {
            font-size: 1.1rem;
            opacity: 0.9;
        }

        .thread-pool-selector {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }

        .selector-content {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .selector-content label {
            font-weight: 600;
            color: #333;
        }

        .selector-content select {
            padding: 10px 15px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 16px;
            background: white;
            cursor: pointer;
            transition: border-color 0.3s;
        }

        .selector-content select:focus {
            outline: none;
            border-color: #667eea;
        }

        .refresh-btn {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 600;
            transition: transform 0.2s;
        }

        .refresh-btn:hover {
            transform: translateY(-2px);
        }

        .dashboard {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            margin-bottom: 30px;
        }

        .card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            transition: transform 0.3s;
        }

        .card:hover {
            transform: translateY(-5px);
        }

        .card-title {
            font-size: 1.3rem;
            font-weight: 700;
            color: #333;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .card-title::before {
            content: '';
            width: 4px;
            height: 25px;
            background: linear-gradient(45deg, #667eea, #764ba2);
            border-radius: 2px;
        }

        .metrics-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
        }

        .metric-item {
            text-align: center;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 10px;
            border-left: 4px solid #667eea;
        }

        .metric-value {
            font-size: 1.8rem;
            font-weight: 700;
            color: #333;
            margin-bottom: 5px;
        }

        .metric-label {
            font-size: 0.9rem;
            color: #666;
            font-weight: 500;
        }

        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
        }

        .status-low { background: #28a745; }
        .status-medium { background: #ffc107; }
        .status-high { background: #fd7e14; }
        .status-critical { background: #dc3545; }

        .progress-bar {
            width: 100%;
            height: 8px;
            background: #e9ecef;
            border-radius: 4px;
            overflow: hidden;
            margin-top: 10px;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(45deg, #667eea, #764ba2);
            border-radius: 4px;
            transition: width 0.5s ease;
        }

        .chart-container {
            height: 500px;
            margin-top: 20px;
            position: relative;
        }
        
        .chart-container canvas {
            image-rendering: -webkit-optimize-contrast;
            image-rendering: -moz-crisp-edges;
            image-rendering: crisp-edges;
            image-rendering: pixelated;
        }
        
        .chart-controls {
            display: flex;
            align-items: center;
            gap: 15px;
            margin-bottom: 15px;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 8px;
            border: 1px solid #e9ecef;
        }
        
        .btn-control {
            padding: 6px 12px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            transition: background-color 0.3s;
        }
        
        .btn-control:hover {
            background: #5a67d8;
        }
        
        .select-control {
            padding: 6px 10px;
            border: 1px solid #d1d5db;
            border-radius: 4px;
            background: white;
            font-size: 12px;
            cursor: pointer;
        }
        
        .chart-help {
            color: #6b7280;
            font-size: 11px;
            margin-left: auto;
        }
        
        .chart-wrapper {
            position: relative;
            height: calc(100% - 60px);
            width: 100%;
        }

        .adjustment-controls {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .control-group {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .control-group label {
            font-weight: 600;
            color: #333;
        }

        .control-group input {
            padding: 10px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 16px;
        }

        .control-group input:focus {
            outline: none;
            border-color: #667eea;
        }

        .adjust-btn {
            background: linear-gradient(45deg, #28a745, #20c997);
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 600;
            margin-top: 15px;
            transition: transform 0.2s;
        }

        .adjust-btn:hover {
            transform: translateY(-2px);
        }

        .history-section {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
        }

        .history-list {
            max-height: 400px;
            overflow-y: auto;
            background: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
        }

        .history-item {
            padding: 10px;
            margin-bottom: 8px;
            background: white;
            border-radius: 6px;
            border-left: 3px solid #667eea;
            font-size: 0.9rem;
            line-height: 1.4;
        }

        .timestamp {
            color: #666;
            font-size: 0.8rem;
        }

        .alert {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-weight: 500;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-danger {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .loading::after {
            content: '';
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-left: 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        @media (max-width: 768px) {
            .dashboard {
                grid-template-columns: 1fr;
            }
            
            .history-section {
                grid-template-columns: 1fr;
            }
            
            .metrics-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
            <div class="header">
                <h1>🚀 动态线程池监控系统</h1>
                <p>实时监控线程池状态，智能调整性能参数</p>
            </div>

        <div class="thread-pool-selector">
            <div class="selector-content">
                <label for="poolSelect">选择线程池:</label>
                <select id="poolSelect">
                    <option value="">请选择线程池...</option>
                </select>
                <button class="refresh-btn" onclick="refreshData()">🔄 刷新数据</button>
            </div>
        </div>

        <div id="alertContainer"></div>

        <div id="mainContent" style="display: none;">
            <div class="dashboard">
                <!-- 基本状态卡片 -->
                <div class="card">
                    <div class="card-title">📊 基本状态</div>
                    <div class="metrics-grid">
                        <div class="metric-item">
                            <div class="metric-value" id="corePoolSize">-</div>
                            <div class="metric-label">核心线程数</div>
                        </div>
                        <div class="metric-item">
                            <div class="metric-value" id="maximumPoolSize">-</div>
                            <div class="metric-label">最大线程数</div>
                        </div>
                        <div class="metric-item">
                            <div class="metric-value" id="activeThreads">-</div>
                            <div class="metric-label">活跃线程数</div>
                        </div>
                        <div class="metric-item">
                            <div class="metric-value" id="currentPoolSize">-</div>
                            <div class="metric-label">当前线程数</div>
                        </div>
                        <div class="metric-item">
                            <div class="metric-value" id="queueCapacity">-</div>
                            <div class="metric-label">队列容量</div>
                        </div>
                    </div>
                </div>

                <!-- 队列状态卡片 -->
                <div class="card">
                    <div class="card-title">📦 队列状态</div>
                    <div class="metrics-grid">
                        <div class="metric-item">
                            <div class="metric-value" id="queueSize">-</div>
                            <div class="metric-label">队列大小</div>
                        </div>
                        <div class="metric-item">
                            <div class="metric-value" id="queueUsageRate">-</div>
                            <div class="metric-label">队列使用率</div>
                            <div class="progress-bar">
                                <div class="progress-fill" id="queueProgress"></div>
                            </div>
                        </div>
                        <div class="metric-item">
                            <div class="metric-value" id="loadLevel">-</div>
                            <div class="metric-label">
                                <span class="status-indicator" id="loadIndicator"></span>
                                负载等级
                            </div>
                        </div>
                        <div class="metric-item">
                            <div class="metric-value" id="threadPoolActivity">-</div>
                            <div class="metric-label">线程活跃度</div>
                            <div class="progress-bar">
                                <div class="progress-fill" id="activityProgress"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="dashboard">
                <!-- 性能指标卡片 -->
                <div class="card">
                    <div class="card-title">⚡ 性能指标</div>
                    <div class="metrics-grid">
                        <div class="metric-item">
                            <div class="metric-value" id="taskSubmitRate">-</div>
                            <div class="metric-label">提交速率 (任务/秒)</div>
                        </div>
                        <div class="metric-item">
                            <div class="metric-value" id="taskCompleteRate">-</div>
                            <div class="metric-label">完成速率 (任务/秒)</div>
                        </div>
                        <div class="metric-item">
                            <div class="metric-value" id="averageWaitTime">-</div>
                            <div class="metric-label">平均等待时间 (ms)</div>
                        </div>
                        <div class="metric-item">
                            <div class="metric-value" id="maxWaitTime">-</div>
                            <div class="metric-label">最大等待时间 (ms)</div>
                        </div>
                    </div>
                </div>

                <!-- 任务统计卡片 -->
                <div class="card">
                    <div class="card-title">📈 任务统计</div>
                    <div class="metrics-grid">
                        <div class="metric-item">
                            <div class="metric-value" id="totalSubmittedTasks">-</div>
                            <div class="metric-label">已提交任务</div>
                        </div>
                        <div class="metric-item">
                            <div class="metric-value" id="totalCompletedTasks">-</div>
                            <div class="metric-label">已完成任务</div>
                        </div>
                        <div class="metric-item">
                            <div class="metric-value" id="totalRejectedTasks">-</div>
                            <div class="metric-label">被拒绝任务</div>
                        </div>
                        <div class="metric-item">
                            <div class="metric-value" id="taskProcessingEfficiency">-</div>
                            <div class="metric-label">处理效率</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 手动调整卡片 -->
            <div class="card">
                <div class="card-title">🔧 手动调整</div>
                <div class="adjustment-controls">
                    <div class="control-group">
                        <label for="newCoreSize">核心线程数:</label>
                        <input type="number" id="newCoreSize" min="1" max="100">
                    </div>
                    <div class="control-group">
                        <label for="newMaxSize">最大线程数:</label>
                        <input type="number" id="newMaxSize" min="1" max="200">
                    </div>
                    <div class="control-group">
                        <label for="newQueueCapacity">队列容量:</label>
                        <input type="number" id="newQueueCapacity" min="1" max="1000">
                    </div>
                    <div class="control-group">
                        <button class="adjust-btn" onclick="adjustThreadPool()">应用调整</button>
                    </div>
                </div>
            </div>

            <!-- 历史记录 -->
            <div class="history-section">
                <div class="card">
                    <div class="card-title">📋 调整历史</div>
                    <div class="history-list" id="adjustmentHistory">
                        <div class="loading">加载历史记录中...</div>
                    </div>
                </div>

                <div class="card">
                    <div class="card-title">📊 指标趋势</div>
                    <div class="chart-container">
                        <div class="chart-controls">
                            <button onclick="resetChartZoom()" class="btn-control">重置缩放</button>
                            <select id="timeRange" onchange="changeTimeRange()" class="select-control">
                                <option value="10">最近10分钟</option>
                                <option value="30">最近30分钟</option>
                                <option value="60" selected>最近1小时</option>
                                <option value="180">最近3小时</option>
                                <option value="360">最近6小时</option>
                                <option value="720">最近12小时</option>
                                <option value="1440">最近24小时</option>
                            </select>
                            <span class="chart-help">提示：鼠标滚轮缩放，Ctrl+拖拽平移</span>
                        </div>
                        <div class="chart-wrapper">
                            <canvas id="trendChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let currentPool = '';
        let refreshInterval;
        let chart = null;
        let chartData = {
            datasets: [
                {
                    label: '队列使用率 (%)',
                    data: [],
                    borderColor: '#667eea',
                    backgroundColor: 'rgba(102, 126, 234, 0.1)',
                    tension: 0.4,
                    yAxisID: 'y'
                },
                {
                    label: '线程活跃度 (%)',
                    data: [],
                    borderColor: '#764ba2',
                    backgroundColor: 'rgba(118, 75, 162, 0.1)',
                    tension: 0.4,
                    yAxisID: 'y'
                },
                {
                    label: '提交速率 (任务/秒)',
                    data: [],
                    borderColor: '#28a745',
                    backgroundColor: 'rgba(40, 167, 69, 0.1)',
                    tension: 0.4,
                    yAxisID: 'y1'
                },
                {
                    label: '完成速率 (任务/秒)',
                    data: [],
                    borderColor: '#ffc107',
                    backgroundColor: 'rgba(255, 193, 7, 0.1)',
                    tension: 0.4,
                    yAxisID: 'y1'
                }
            ]
        };

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadThreadPools();
            setupAutoRefresh();
            initChart();
        });
        
        // 初始化Chart.js图表
        function initChart() {
            // 检查Chart.js是否加载
            if (typeof Chart === 'undefined') {
                console.error('Chart.js not loaded');
                return;
            }
            
            const canvas = document.getElementById('trendChart');
            const ctx = canvas.getContext('2d');
            
            // 设置高分辨率显示，解决图表模糊问题
            const devicePixelRatio = window.devicePixelRatio || 1;
            const rect = canvas.getBoundingClientRect();
            canvas.width = rect.width * devicePixelRatio;
            canvas.height = rect.height * devicePixelRatio;
            ctx.scale(devicePixelRatio, devicePixelRatio);
            canvas.style.width = rect.width + 'px';
            canvas.style.height = rect.height + 'px';
            
            // 注册Chart.js插件
            try {
                if (typeof ChartZoom !== 'undefined') {
                    Chart.register(ChartZoom);
                    console.log('ChartZoom plugin registered');
                } else if (typeof window.ChartZoom !== 'undefined') {
                    Chart.register(window.ChartZoom);
                    console.log('Window ChartZoom plugin registered');
                } else {
                    console.warn('ChartZoom plugin not found');
                }
            } catch (e) {
                console.warn('Failed to register zoom plugin:', e);
            }
            
            chart = new Chart(ctx, {
                type: 'line',
                data: chartData,
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    devicePixelRatio: window.devicePixelRatio || 1,
                    animation: {
                        duration: 300
                    },
                    interaction: {
                        mode: 'index',
                        intersect: false,
                    },
                    plugins: {
                        title: {
                            display: true,
                            text: '线程池指标趋势图',
                            font: {
                                size: 16,
                                weight: 'bold'
                            }
                        },
                        legend: {
                            display: true,
                            position: 'top'
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false,
                            backgroundColor: 'rgba(0, 0, 0, 0.8)',
                            titleColor: '#fff',
                            bodyColor: '#fff',
                            borderColor: '#667eea',
                            borderWidth: 1,
                            cornerRadius: 8,
                            displayColors: true,
                            callbacks: {
                                title: function(context) {
                                    if (context[0] && context[0].parsed && context[0].parsed.x) {
                                        return new Date(context[0].parsed.x).toLocaleString('zh-CN');
                                    }
                                    return '';
                                },
                                label: function(context) {
                                    let label = context.dataset.label || '';
                                    if (label) {
                                        label += ': ';
                                    }
                                    if (context.parsed.y !== null) {
                                        if (context.dataset.yAxisID === 'y') {
                                            label += context.parsed.y.toFixed(2) + '%';
                                        } else {
                                            label += context.parsed.y.toFixed(2) + ' 任务/秒';
                                        }
                                    }
                                    return label;
                                }
                            }
                        },
                        zoom: {
                            pan: {
                                enabled: true,
                                mode: 'x',
                                modifierKey: 'ctrl'
                            },
                            zoom: {
                                wheel: {
                                    enabled: true,
                                },
                                pinch: {
                                    enabled: true
                                },
                                mode: 'x',
                                onZoomComplete: function({chart}) {
                                    // 可以在这里添加缩放完成后的回调
                                }
                            }
                        }
                    },
                    scales: {
                        x: {
                            type: 'time',
                            time: {
                                displayFormats: {
                                    second: 'HH:mm:ss',
                                    minute: 'HH:mm',
                                    hour: 'MM-dd HH:mm',
                                    day: 'MM-dd'
                                },
                                tooltipFormat: 'yyyy-MM-dd HH:mm:ss'
                            },
                            title: {
                                display: true,
                                text: '时间'
                            },
                            grid: {
                                color: 'rgba(0, 0, 0, 0.1)'
                            }
                        },
                        y: {
                            type: 'linear',
                            display: true,
                            position: 'left',
                            title: {
                                display: true,
                                text: '百分比 (%)'
                            },
                            min: 0,
                            max: 100,
                            grid: {
                                color: 'rgba(0, 0, 0, 0.1)'
                            }
                        },
                        y1: {
                            type: 'linear',
                            display: true,
                            position: 'right',
                            title: {
                                display: true,
                                text: '速率 (任务/秒)'
                            },
                            min: 0,
                            grid: {
                                drawOnChartArea: false,
                            },
                        }
                    },
                    elements: {
                        point: {
                            radius: 2,
                            hoverRadius: 5,
                            borderWidth: 1,
                            backgroundColor: 'rgba(255, 255, 255, 0.8)'
                        },
                        line: {
                            borderWidth: 2,
                            tension: 0.3
                        }
                    }
                }
            });
            
            console.log('Chart initialized:', chart);
            
            // 监听窗口大小变化，重新调整图表分辨率
            window.addEventListener('resize', function() {
                if (chart) {
                    setTimeout(() => {
                        const canvas = document.getElementById('trendChart');
                        const ctx = canvas.getContext('2d');
                        const devicePixelRatio = window.devicePixelRatio || 1;
                        const rect = canvas.getBoundingClientRect();
                        canvas.width = rect.width * devicePixelRatio;
                        canvas.height = rect.height * devicePixelRatio;
                        ctx.scale(devicePixelRatio, devicePixelRatio);
                        canvas.style.width = rect.width + 'px';
                        canvas.style.height = rect.height + 'px';
                        chart.resize();
                    }, 100);
                }
            });
        }
        
        // 重置图表缩放
        function resetChartZoom() {
            if (chart) {
                chart.resetZoom();
            }
        }
        
        // 切换时间范围
        function changeTimeRange() {
            const timeRange = document.getElementById('timeRange').value;
            const minutes = parseInt(timeRange);
            const cutoffTime = new Date(Date.now() - minutes * 60 * 1000);
            
            if (chart) {
                // 过滤数据，只保留指定时间范围内的数据
                chart.data.datasets.forEach(dataset => {
                    dataset.data = dataset.data.filter(point => new Date(point.x) >= cutoffTime);
                });
                chart.update();
            }
        }

        // 加载线程池列表
        async function loadThreadPools() {
            try {
                const response = await fetch('http://localhost:8080/threadpool/api/pools');
                const pools = await response.json();
                
                const select = document.getElementById('poolSelect');
                select.innerHTML = '<option value="">请选择线程池...</option>';
                
                pools.forEach(pool => {
                    const option = document.createElement('option');
                    option.value = pool;
                    option.textContent = pool;
                    select.appendChild(option);
                });
                
                select.addEventListener('change', function() {
                    currentPool = this.value;
                    if (currentPool) {
                        document.getElementById('mainContent').style.display = 'block';
                        refreshData();
                    } else {
                        document.getElementById('mainContent').style.display = 'none';
                    }
                });
            } catch (error) {
                showAlert('加载线程池列表失败: ' + error.message, 'danger');
            }
        }

        // 刷新数据
        async function refreshData() {
            if (!currentPool) return;
            
            try {
                const response = await fetch(`http://localhost:8080/threadpool/api/pools/${currentPool}/status`);
                const data = await response.json();
                
                if (data.error) {
                    showAlert(data.error, 'danger');
                    return;
                }
                
                updateMetrics(data.metrics);
                loadAdjustmentHistory();
                updateChart(data.metrics);
                
            } catch (error) {
                showAlert('刷新数据失败: ' + error.message, 'danger');
            }
        }

        // 更新指标显示
        function updateMetrics(metrics) {
            // 基本状态
            document.getElementById('corePoolSize').textContent = metrics.corePoolSize;
            document.getElementById('maximumPoolSize').textContent = metrics.maximumPoolSize;
            document.getElementById('activeThreads').textContent = metrics.activeThreads;
            document.getElementById('currentPoolSize').textContent = metrics.currentPoolSize;
            document.getElementById('queueCapacity').textContent = metrics.queueCapacity;
            
            // 队列状态
            document.getElementById('queueSize').textContent = metrics.queueSize;
            document.getElementById('queueUsageRate').textContent = (metrics.queueUsageRate * 100).toFixed(1) + '%';
            document.getElementById('queueProgress').style.width = (metrics.queueUsageRate * 100) + '%';
            
            // 负载等级
            const loadLevel = metrics.loadLevel;
            document.getElementById('loadLevel').textContent = getLoadLevelText(loadLevel);
            updateLoadIndicator(loadLevel);
            
            // 线程活跃度
            document.getElementById('threadPoolActivity').textContent = (metrics.threadPoolActivity * 100).toFixed(1) + '%';
            document.getElementById('activityProgress').style.width = (metrics.threadPoolActivity * 100) + '%';
            
            // 性能指标
            document.getElementById('taskSubmitRate').textContent = metrics.taskSubmitRate.toFixed(2);
            document.getElementById('taskCompleteRate').textContent = metrics.taskCompleteRate.toFixed(2);
            document.getElementById('averageWaitTime').textContent = metrics.averageWaitTime.toFixed(2);
            document.getElementById('maxWaitTime').textContent = metrics.maxWaitTime;
            
            // 任务统计
            document.getElementById('totalSubmittedTasks').textContent = metrics.totalSubmittedTasks;
            document.getElementById('totalCompletedTasks').textContent = metrics.totalCompletedTasks;
            document.getElementById('totalRejectedTasks').textContent = metrics.recentRejectedTasks || 0;
            document.getElementById('taskProcessingEfficiency').textContent = (metrics.taskProcessingEfficiency * 100).toFixed(1) + '%';
            
            // 更新输入框的当前值
            document.getElementById('newCoreSize').placeholder = `当前: ${metrics.corePoolSize}`;
            document.getElementById('newMaxSize').placeholder = `当前: ${metrics.maximumPoolSize}`;
        }

        // 获取负载等级文本
        function getLoadLevelText(level) {
            switch(level) {
                case 1: return '低负载';
                case 2: return '中等负载';
                case 3: return '高负载';
                case 4: return '过载';
                default: return '未知';
            }
        }

        // 更新负载指示器
        function updateLoadIndicator(level) {
            const indicator = document.getElementById('loadIndicator');
            indicator.className = 'status-indicator';
            
            switch(level) {
                case 1: indicator.classList.add('status-low'); break;
                case 2: indicator.classList.add('status-medium'); break;
                case 3: indicator.classList.add('status-high'); break;
                case 4: indicator.classList.add('status-critical'); break;
            }
        }

        // 加载调整历史
        async function loadAdjustmentHistory() {
            if (!currentPool) return;
            
            try {
                const response = await fetch(`http://localhost:8080/threadpool/api/pools/${currentPool}/adjustments`);
                const history = await response.json();
                
                const container = document.getElementById('adjustmentHistory');
                if (history.length === 0) {
                    container.innerHTML = '<div class="history-item">暂无调整记录</div>';
                } else {
                    container.innerHTML = history.slice(-100).reverse().map(item => {
                        // 格式化时间显示
                        const formattedItem = formatAdjustmentHistoryItem(item);
                        return `<div class="history-item">${formattedItem}</div>`;
                    }).join('');
                }
            } catch (error) {
                console.error('加载调整历史失败:', error);
            }
        }
        
        // 格式化调整历史项目
        function formatAdjustmentHistoryItem(item) {
            // 匹配时间格式: Mon Jun 30 10:03:02 GMT+08:00 2025:
            const timeRegex = /^([A-Za-z]{3} [A-Za-z]{3} \d{1,2} \d{2}:\d{2}:\d{2} GMT[+-]\d{2}:\d{2} \d{4}):\s*(.*)$/;
            const match = item.match(timeRegex);
            
            if (match) {
                const dateStr = match[1];
                const content = match[2];
                
                try {
                    const date = new Date(dateStr);
                    const formattedTime = date.toLocaleString('zh-CN', {
                        year: 'numeric',
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit',
                        minute: '2-digit',
                        second: '2-digit'
                    });
                    return `${formattedTime}: ${content}`;
                } catch (e) {
                    // 如果时间解析失败，返回原始内容
                    return item;
                }
            }
            
            return item;
        }

        // 手动调整线程池
        async function adjustThreadPool() {
            if (!currentPool) return;
            
            const coreSize = document.getElementById('newCoreSize').value;
            const maxSize = document.getElementById('newMaxSize').value;
            const queueCapacity = document.getElementById('newQueueCapacity').value;
            
            if (!coreSize && !maxSize && !queueCapacity) {
                showAlert('请至少填写一个调整参数', 'danger');
                return;
            }
            
            const params = new URLSearchParams();
            if (coreSize) params.append('coreSize', coreSize);
            if (maxSize) params.append('maxSize', maxSize);
            if (queueCapacity) params.append('queueCapacity', queueCapacity);
            
            try {
                const response = await fetch(`http://localhost:8080/threadpool/api/pools/${currentPool}/adjust`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: params
                });
                
                const result = await response.json();
                
                if (result.success) {
                    showAlert('调整成功!', 'success');
                    // 清空输入框
                    document.getElementById('newCoreSize').value = '';
                    document.getElementById('newMaxSize').value = '';
                    document.getElementById('newQueueCapacity').value = '';
                    // 刷新数据
                    setTimeout(refreshData, 1000);
                } else {
                    showAlert('调整失败: ' + result.error, 'danger');
                }
            } catch (error) {
                showAlert('调整失败: ' + error.message, 'danger');
            }
        }

        // 更新图表
        function updateChart(metrics) {
            //console.log('updateChart called with metrics:', metrics);
            if (!chart) {
                console.log('Chart not initialized');
                return;
            }
            
            const now = new Date();
            
            // 添加新数据点
            chart.data.datasets[0].data.push({
                x: now,
                y: metrics.queueUsageRate * 100
            });
            chart.data.datasets[1].data.push({
                x: now,
                y: metrics.threadPoolActivity * 100
            });
            chart.data.datasets[2].data.push({
                x: now,
                y: metrics.taskSubmitRate
            });
            chart.data.datasets[3].data.push({
                x: now,
                y: metrics.taskCompleteRate
            });
            
            // 保留最近50个数据点
            chart.data.datasets.forEach(dataset => {
                if (dataset.data.length > 50) {
                    dataset.data.shift();
                }
            });
            
            chart.update('none');
        }



        // 显示提示信息
        function showAlert(message, type) {
            const container = document.getElementById('alertContainer');
            const alert = document.createElement('div');
            alert.className = `alert alert-${type}`;
            alert.textContent = message;
            
            container.innerHTML = '';
            container.appendChild(alert);
            
            setTimeout(() => {
                alert.remove();
            }, 5000);
        }

        // 设置自动刷新
        function setupAutoRefresh() {
            refreshInterval = setInterval(() => {
                if (currentPool) {
                    refreshData();
                }
            }, 3000); // 每3秒刷新一次
        }

        // 页面卸载时清理定时器
        window.addEventListener('beforeunload', function() {
            if (refreshInterval) {
                clearInterval(refreshInterval);
            }
        });
    </script>
</body>
</html>